<!-- 工站单价配置 -->
<template>
  <basic-container>
    <el-tabs v-model="activeName" style="margin: 0 10px" @tab-click="handleTabClick">
      <el-tab-pane label="工站单价" name="station"> </el-tab-pane>
      <el-tab-pane label="工段单价" name="section"> </el-tab-pane>
      <avue-crud
        v-if="activeName === 'station'"
        :option="option"
        :table-loading="loading"
        :data="data"
        :defaults.sync="defaults"
        :page.sync="page"
        :permission="permissionList"
        v-model="form"
        ref="crud"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
      >
        <template slot="menuLeft">
          <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.stationPriceConfig_add" @click="handleAdd">新 增</el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.stationPriceConfig_delete" plain @click="handleDelete">作 废</el-button>
          <el-button type="success" size="small" icon="el-icon-setting" v-if="permission.stationPriceConfig_audit" @click="handleAudit" v-preventReClick>审核</el-button>
        </template>
        <template slot="menuRight">
          <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
        </template>
        <!-- 操作列 -->
        <template slot="menu" slot-scope="{ row }">
          <el-button type="text" size="small" icon="el-icon-view" v-if="permission.stationPriceConfig_view" @click="handleView(row)">详情</el-button>
          <el-button type="text" size="small" icon="el-icon-edit" v-if="permission.stationPriceConfig_edit" @click="handleEdit(row)" :disabled="row.status">编辑</el-button>
          <el-button type="text" size="small" icon="el-icon-delete" v-if="permission.stationPriceConfig_delete" @click="handleDel(row)" :disabled="row.status == 3"
            >作废</el-button
          >
        </template>
      </avue-crud>
      <selection-price v-if="activeName === 'section'"> </selection-price>
    </el-tabs>

    <el-dialog
      append-to-body
      width="60%"
      top="5vh"
      :title="stationPriceDialog.title"
      :visible.sync="stationPriceDialog.visible"
      @open="stationPriceDialogOpen"
      @close="stationPriceDialogClose"
    >
      <!-- 基本信息 -->
      <!-- {{ stationPriceDialog.data }} -->
      <div
        :element-loading-text="stationPriceDialogLoadingText"
        v-loading="stationPriceDialogLoading"
        element-loading-spinner="el-icon-loading"
        element-loading-background="#ffffffe6"
      >
        <h1 class="subTitle"><i class="el-icon-vertical-bar mr10"></i>基本信息</h1>
        <avue-form v-model="stationPriceDialog.basicInfoFormModel" ref="basicInfoForm" key="basicInfoFormKey" :option="stationPriceDialog.basicInfoFormOptions"> </avue-form>
        <!-- 工站单价 -->
        <h1 class="subTitle"><i class="el-icon-vertical-bar mr10"></i>工站单价</h1>
        <avue-crud
          ref="stationPriceCrud"
          v-model="stationPriceDialog.form"
          :option="stationPriceDialog.option"
          :table-loading="stationPriceDialog.loading"
          :data="stationPriceDialog.data"
          :defaults.sync="stationPriceDialog.defaults"
          @selection-change="groupSelectionChange"
          @row-save="rowPriceSave"
          @row-update="rowPriceUpdate"
          @row-del="handleDelPriceRow"
          :before-open="beforePriceOpen"
          :before-close="beforePriceClose"
        >
          <template slot="menuLeft">
            <el-button type="primary" size="small" :disabled="isViewButtonStatus" icon="el-icon-plus" @click="handleInsert">新增工序</el-button>
          </template>
          <template slot="menu" slot-scope="{ row }">
            <el-button type="text" size="small" v-if="!row.parentId" icon="el-icon-plus" @click="handleSubInsert(row)">新增明细</el-button>
          </template>
        </avue-crud>
        <!-- 合计 -->
        <h1 class="subTitle"></h1>
        <avue-form v-model="stationPriceDialog.amountFormModel" ref="amountForm" key="amountFormKey" :option="stationPriceDialog.amountFormOptions"> </avue-form>
      </div>

      <div slot="footer" class="dialog-footer" v-if="!isViewButtonStatus">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="submitForm" v-preventReClick>保存</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="closeDialog">取消</el-button>
      </div>
    </el-dialog>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  remove,
  removeRoute,
  removeMaterial,
  cancellation,
  priceAudit,
  processProductRouteByPartno,
  calculateRoutePrice,
  calculatePrice
} from '@/api/product/stationPriceConfig';
import { mapGetters } from 'vuex';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import { validateContacts } from '@/mixins/validateContacts.js';
import { deepClone, compareTime } from '@/util/util';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
import selectionPrice from '@/views/product/selectionPrice.vue';
export default {
  name: 'StationPriceConfig',
  components: {
    selectionPrice,
    GlobalModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    const that = this;
    var effectiveFrom = (rule, value, callback) => {
      if (!this.stationPriceDialog.basicInfoFormModel.effectiveFrom) {
        callback(new Error('请输入生效时间'));
      }
      if (!this.stationPriceDialog.basicInfoFormModel.effectiveTo) {
        callback();
      } else if (this.stationPriceDialog.basicInfoFormModel.effectiveTo && value) {
        let result = compareTime(this.stationPriceDialog.basicInfoFormModel.effectiveTo, value);
        if (result === 2) {
          callback(new Error('生效时间不能大于失效时间'));
        } else if (result === 0) {
          callback();
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    var effectiveTo = (rule, value, callback) => {
      if (!this.stationPriceDialog.basicInfoFormModel.effectiveTo) {
        callback(new Error('请输入失效时间'));
      }
      if (!this.stationPriceDialog.basicInfoFormModel.effectiveFrom) {
        callback();
      } else if (this.stationPriceDialog.basicInfoFormModel.effectiveFrom && value) {
        let result = compareTime(this.stationPriceDialog.basicInfoFormModel.effectiveFrom, value);
        if (result === 1) {
          callback(new Error('失效时间不能小于生效时间'));
        } else if (result === 0) {
          callback();
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      activeName: 'station',
      pageCode: 'STATION_PRICE_CONFIG',
      editData: null,
      processId: '', // 产品工艺ID
      routeList: [], // 工站集合
      visibile: false,
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      form: {
        principle: '',
        principleName: ''
      },
      defaults: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 510px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        addBtn: false,
        menu: true,
        menuWidth: 200,
        selection: true,
        labelWidth: 120,
        dialogClickModal: false,
        columnBtn: false,
        column: [
          {
            label: '产品名称',
            prop: 'partName',
            search: true
          },
          {
            label: '产品编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '产品类型',
            prop: 'partType',
            type: 'search',
            disabled: true,
            searchType: 'input'
          },
          {
            label: '产品型号',
            prop: 'partModel',
            type: 'search',
            disabled: true
          },
          {
            label: '总价',
            prop: 'totalPrice',
            disabled: true
          },
          {
            label: '系数',
            prop: 'rate',
            type: 'search',
            minRows: 0,
            disabled: true,
            searchType: 'input'
          },
          {
            label: '折后总价',
            prop: 'discountPrice',
            rules: [{ validator: validateContacts, trigger: 'blur' }]
          },
          {
            label: '有效期',
            prop: 'effectiveTime',
            width: 200
          },
          {
            label: '审核状态',
            prop: 'status',
            width: 100,
            search: true,
            type: 'select',
            minRows: 3,
            span: 24,
            dicData: [
              { label: '已审核', value: 1 },
              { label: '未审核', value: 0 },
              { label: '已作废', value: 3 },
              { label: '已失效', value: 4 }
            ],
            html: true,
            formatter: (val) => {
              switch (val.status) {
                case 4:
                  return `<span class="stateWords-warning">已失效</span>`;
                case 3:
                  return `<span class="stateWords-default">已作废</span>`;
                case 1:
                  return `<span class="stateWords-success">已审核</span>`;
                case 0:
                  return `<span class="stateWords-danger">未审核</span>`;
                default:
                  break;
              }
            }
          }
        ]
      },
      data: [],
      parentId: null,
      stationPriceDialogLoading: false,
      stationPriceDialogLoadingText: '折后总价计算中，请稍后...',
      stationPriceDialog: {
        visible: false,
        title: '新增工站单价',
        // 基本信息
        basicInfoFormModel: {},
        basicInfoFormOptions: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '产品编码',
              prop: 'partNo',
              searchType: 'input',
              type: 'search',
              disabled: true,
              rules: [
                {
                  required: true,
                  message: '请输入产品编码',
                  trigger: 'blur'
                }
              ],
              appendClick: () => {
                if (this.isViewButtonStatus) return;
                this.openUserCommonModal({
                  type: 'partNo'
                });
              }
            },
            {
              label: '产品名称',
              disabled: true,
              prop: 'partName'
            },
            {
              label: '产品类型',
              disabled: true,
              prop: 'categoryName'
            },
            {
              label: '产品型号',
              disabled: true,
              prop: 'partModel'
            },
            {
              label: '生效时间',
              prop: 'effectiveFrom',
              type: 'date',
              disabled: false,
              format: 'yyyy-MM-dd',
              valueFormat: 'yyyy-MM-dd',
              rules: [
                {
                  required: true,
                  validator: effectiveFrom,
                  trigger: 'change'
                }
              ]
            },
            {
              label: '失效时间',
              prop: 'effectiveTo',
              type: 'date',
              disabled: false,
              format: 'yyyy-MM-dd',
              valueFormat: 'yyyy-MM-dd',
              rules: [
                {
                  required: true,
                  validator: effectiveTo,
                  trigger: 'change'
                }
              ]
            }
          ]
        },
        // 工站单价
        form: {},
        option: {
          tip: false,
          height: 300,
          calcHeight: 30,
          maxHeight: 300,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: false,
          addBtn: false,
          editBtn: true,
          delBtn: true,
          viewBtn: false,
          refreshBtn: false,
          rowKey: 'id',
          rowParentKey: 'parentId',
          // cellBtn: true,
          columnBtn: false,
          menu: true,
          menuWidth: 250,
          selection: false,
          dialogClickModal: false,
          column: [
            {
              label: '工站名称',
              prop: 'routeName',
              addDisplay: false,
              editDisplay: false
            },
            {
              label: '物料编码',
              prop: 'partNo',
              searchType: 'input',
              type: 'search',
              disabled: true,
              order: 1,
              span: 24,
              rules: [
                {
                  required: true,
                  message: '请选择物料编码',
                  trigger: 'change'
                }
              ],
              appendClick: () => {
                this.openUserCommonModal({
                  type: 'pricepartNo'
                });
              }
            },
            {
              label: '工站名称',
              prop: 'processRouteId',
              hide: true,
              type: 'select',
              span: 24,
              order: 2,
              dicData: [],
              rules: [
                {
                  required: true,
                  message: '请选择工站名称',
                  trigger: 'change'
                }
              ],
              change: ({ value, column }) => {
                if (value) {
                  let changeRouteArr = column.dicData.filter((d) => d.value == value);
                  if (changeRouteArr && changeRouteArr.length > 0) {
                    this.stationPriceDialog.form.routeName = changeRouteArr[0].label;
                    this.stationPriceDialog.form.routeCode = changeRouteArr[0].routeCode;
                    this.stationPriceDialog.form.routeType = changeRouteArr[0].routeType;
                    this.stationPriceDialog.form.sequence = changeRouteArr[0].sequence;
                  }
                }
              }
            },
            {
              label: '加工内容',
              prop: 'routeDescription',
              span: 24,
              rules: [
                {
                  required: true,
                  message: '请输入加工内容',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '工站单价',
              prop: 'price',
              type: 'number',
              value: 0,
              disabled: true,
              precision: 2,
              span: 24,
              minRows: 0,
              rules: [
                {
                  required: true,
                  message: '请输入工站单价',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '备注',
              prop: 'remark',
              type: 'textarea',
              span: 24,
              minRows: 3,
              maxRows: 3,
              cell: true
            }
          ]
        },
        query: {
          shiftGroupId: ''
        },
        selectionList: [],
        loading: false,
        defaults: {},
        submitData: null,
        data: [],
        // 金额合计
        amountFormModel: {},
        amountFormOptions: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '合计',
              prop: 'totalPrice',
              span: 8,
              disabled: true,
              labelWidth: 60
            },
            {
              label: '系数',
              prop: 'rate',
              type: 'number',
              disabled: false,
              span: 8,
              value: 100,
              controls: false,
              labelWidth: 60,
              rules: [
                {
                  required: true,
                  message: '请输入系数',
                  trigger: 'blur'
                }
              ],
              blur: ({ value, column }) => {
                if (value) {
                  this.changeRate(value);
                }
              }
            },
            {
              label: '折后总价',
              prop: 'discountPrice',
              disabled: true,
              span: 8,
              labelWidth: 80
            }
          ]
        }
      }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.stationPriceConfig_add, false),
        viewBtn: this.vaildData(this.permission.stationPriceConfig_view, false),
        delBtn: this.vaildData(this.permission.stationPriceConfig_delete, false),
        editBtn: this.vaildData(this.permission.stationPriceConfig_edit, false),
        auditBtn: this.vaildData(this.permission.stationPriceConfig_audit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      // return ids.join(',');
      return ids;
    },
    isViewButtonStatus() {
      return this.stationPriceDialog.title === '工站单价详情';
    },
    isEditButtonStatus() {
      return this.stationPriceDialog.title === '编辑工站单价';
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据作废?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return cancellation([row.id]);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据作废?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return cancellation(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        if (data.records) {
          this.data = data.records;
        }
        this.loading = false;
        this.selectionClear();
      });
    },
    openUserCommonModal(params) {
      let { type } = params;
      switch (type) {
        // 产品编码
        case 'partNo':
          this.modalName = 'partNoModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择产品信息（双击进行选择）',
            url: '/api/mes-product/processprice/filter-part-has-process-route',
            // query: {
            //   // partType: 'PRODUCT', // partType: 'PRODUCT'成品 / 原材料'MATERIAL' 半成品:SEMIFINISHED
            //   semifinished: true // semifinished:false 原材料 true 在制品（半成品，成品）
            // },
            isPage: true,
            rowSelectionType: 'single',
            menuWidth: 100,
            templateName: 'FILTERPARTMASTER'
          };
          break;
        // 单价里的物料
        case 'pricepartNo':
          this.modalName = 'pricepartNoModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择产品信息（双击进行选择）',
            url: '/api/mes-admin/part-master/page',
            query: {
              // partType: 'PRODUCT', // partType: 'PRODUCT'成品 / 原材料'MATERIAL' 半成品:SEMIFINISHED
              semifinished: false // semifinished:false 原材料 true 在制品（半成品，成品）
            },
            isPage: true,
            rowSelectionType: 'single',
            menuWidth: 100,
            templateName: 'PARTMASTER'
          };
          break;
        default:
          break;
      }
    },
    // 获取选择的模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'partNoModal':
          this.visibile = false;
          this.stationPriceDialog.basicInfoFormModel.partMasterId = this._get(rowData, 'id', '');
          this.stationPriceDialog.basicInfoFormModel.partNo = this._get(rowData, 'partNo', '');
          this.stationPriceDialog.basicInfoFormModel.partName = this._get(rowData, 'partName', '');
          this.stationPriceDialog.basicInfoFormModel.categoryName = this._get(rowData, 'categoryName', '');
          this.stationPriceDialog.basicInfoFormModel.partModel = this._get(rowData, 'partModel', '');
          this.stationPriceDialog.basicInfoFormModel.partType = this._get(rowData, 'partType', '');
          // 根据产品编码，查询产品工艺
          this.getRouteList(this.stationPriceDialog.basicInfoFormModel.partNo);
          break;
        case 'pricepartNoModal':
          this.visibile = false;
          this.stationPriceDialog.form.partMasterId = this._get(rowData, 'id', '');
          // this.stationPriceDialog.form.partName = this._get(rowData, 'name', '');
          this.stationPriceDialog.form.partNo = this._get(rowData, 'partNo', '');
          break;
        default:
          break;
      }
    },
    // 根据产品编码，查询产品工艺
    getRouteList(partNo) {
      processProductRouteByPartno(partNo)
        .then((res) => {
          let data = res.data.data;
          this.routeList = data.map((d) => {
            return {
              value: d.id,
              label: d.name,
              routeCode: d.code,
              routeType: d.routeType,
              sequence: d.sequence
            };
          });
          if (data && data.length > 0) {
            this.processId = data[0].processId;
          }
          let columns = this.stationPriceDialog.option.column;
          let processRouteIdIndex = columns.findIndex((c) => c.prop == 'processRouteId');
          this.stationPriceDialog.option.column[processRouteIdIndex].dicData = this.routeList;
        })
        .catch(() => {});
    },
    // 新增
    handleAdd() {
      this.handleType('新增工站单价', false);
    },
    // 查看
    handleView(row) {
      this.handleType('工站单价详情', true);
      this.getDetailData(row);
    },
    // 编辑
    handleEdit(row) {
      this.$set(this.stationPriceDialog.amountFormOptions.column[1], 'disabled', false);
      this.handleType('编辑工站单价', false);
      this.getDetailData(row);
    },
    // 获取详情数据
    getDetailData(row) {
      this.stationPriceDialogLoading = true;
      this.stationPriceDialogLoadingText = '数据加载中，请稍后...';
      getDetail(row.id)
        .then((res) => {
          let data = res.data.data;
          this.editData = this.deepClone(data);
          // 基本信息
          this.stationPriceDialog.basicInfoFormModel.partNo = data.partNo;
          this.stationPriceDialog.basicInfoFormModel.partName = data.partName;
          this.stationPriceDialog.basicInfoFormModel.categoryName = data.partType;
          this.stationPriceDialog.basicInfoFormModel.partModel = data.partModel;
          this.stationPriceDialog.basicInfoFormModel.effectiveFrom = data.effectiveFrom;
          this.stationPriceDialog.basicInfoFormModel.effectiveTo = data.effectiveTo;

          // 合计
          this.stationPriceDialog.amountFormModel.totalPrice = data.totalPrice;
          this.stationPriceDialog.amountFormModel.rate = data.rate;
          this.stationPriceDialog.amountFormModel.discountPrice = data.discountPrice;

          // 根据产品编码，查询产品工艺
          this.getRouteList(this.stationPriceDialog.basicInfoFormModel.partNo);

          // 工站单价
          // 处理成树结构
          data.routePriceList.forEach((route) => {
            route.parentId = null;
            route.children = route.materialPriceList;
            if (route.children && route.children.length > 0) {
              route.children.forEach((mater) => {
                mater.parentId = route.id;
                mater.routeDescription = mater.description;
              });
            }
          });
          this.stationPriceDialog.data = data.routePriceList;
        })
        .catch((err) => {})
        .finally(() => {
          this.stationPriceDialogLoading = false;
        });
    },
    handleType(name, status) {
      this.stationPriceDialog.visible = true;
      this.stationPriceDialog.title = name;
      this.stationPriceDialog.option.menu = !status; // 操作列
      let columns = this.stationPriceDialog.basicInfoFormOptions.column;
      let effectiveFromIndex = columns.findIndex((c) => c.prop == 'effectiveFrom');
      let effectiveToIndex = columns.findIndex((c) => c.prop == 'effectiveTo');
      this.$nextTick(() => {
        columns[effectiveFromIndex].disabled = status;
        columns[effectiveToIndex].disabled = status;
        // 合计：系数
        this.$set(this.stationPriceDialog.amountFormOptions.column[1], 'disabled', status);
      });
    },
    // 删除
    handleDel(row) {
      this.$refs.crud.rowDel(row);
    },
    // 审核
    handleAudit() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      let isAllowAudit = this.selectionList.every((list) => list.status != 1);
      if (!isAllowAudit) {
        this.$message.warning('勾选数据中存在已审核数据，请重新选择');
        return;
      }
      priceAudit(this.ids)
        .then(() => {
          this.$message.success('审核成功');
          this.onLoad(this.page);
        })
        .catch(() => {});
    },
    // 工站单价 工序 插入
    handleInsert() {
      if (!this.stationPriceDialog.basicInfoFormModel.partNo) {
        this.$message.warning('请先选择基础信息中的产品编码！');
        return;
      }
      let remainRouteList = this.routeList.filter((r) => !this.stationPriceDialog.data.map((d) => d.processRouteId).includes(r.value));

      this.parentId = null;

      let columns = this.stationPriceDialog.option.column;
      let processRouteIdIndex = columns.findIndex((c) => c.prop == 'processRouteId');
      let partNoIndex = columns.findIndex((c) => c.prop == 'partNo');
      let priceIndex = columns.findIndex((c) => c.prop == 'price');

      this.stationPriceDialog.option.column[processRouteIdIndex].dicData = remainRouteList;
      // 工站名称显示 物料名称隐藏
      columns[processRouteIdIndex].display = true;
      columns[partNoIndex].display = false;
      // 工站单价 禁止输入
      columns[priceIndex].disabled = true;

      this.$refs.stationPriceCrud.rowAdd();
    },
    // 工站单价 明细 插入
    handleSubInsert(row) {
      this.parentId = row.id;

      let columns = this.stationPriceDialog.option.column;
      let processRouteIdIndex = columns.findIndex((c) => c.prop == 'processRouteId');
      let partNoIndex = columns.findIndex((c) => c.prop == 'partNo');
      let priceIndex = columns.findIndex((c) => c.prop == 'price');
      // 工站名称隐藏 物料名称显示
      columns[processRouteIdIndex].display = false;
      columns[partNoIndex].display = true;
      // 工站单价 允许输入
      columns[priceIndex].disabled = false;

      this.$refs.stationPriceCrud.rowAdd();
    },
    // 工站单价 删除
    async handleDelPriceRow(row, index, done) {
      // 明细删除
      if (row.parentId) {
        // if (row.id && !row.id.includes('-id')) {
        //   removeMaterial([row.id])
        //     .then(async () => {
        //       done();
        //       let children = this.stationPriceDialog.data.filter((d) => d.id == row.parentId);
        //       let childrenIndex = this.stationPriceDialog.data.findIndex((d) => d.id == row.parentId);
        //       if (children && children.length > 0) {
        //         let prices = children[0].children ? children[0].children.map((c) => c.price) : [];
        //         let result = await calculateRoutePrice(prices);
        //         if (result.data.code === 200) {
        //           let data = result.data.data || 0;
        //           // 修改工序价格
        //           this.$set(this.stationPriceDialog.data[childrenIndex], 'price', data);
        //           await this.calculateTotalPrice();
        //           await this.stationPriceOnLoad();
        //         }
        //       }
        //     })
        //     .catch(() => {});
        // } else {
        //   done();
        // }
        done();
        let children = this.stationPriceDialog.data.filter((d) => d.id == row.parentId);
        let childrenIndex = this.stationPriceDialog.data.findIndex((d) => d.id == row.parentId);
        if (children && children.length > 0) {
          let prices = children[0].children ? children[0].children.map((c) => c.price) : [];
          let result = await calculateRoutePrice(prices);
          if (result.data.code === 200) {
            let data = result.data.data || 0;
            // 修改工序价格
            this.$set(this.stationPriceDialog.data[childrenIndex], 'price', data);
          }
        }
        await this.calculateTotalPrice();
        await this.stationPriceOnLoad();
      } else {
        done();
        await this.calculateTotalPrice();
        await this.stationPriceOnLoad();
        // 工序删除
        // if (row.id && !row.id.includes('-id')) {
        //   removeRoute([row.id])
        //     .then(async () => {
        //       done();
        //       await this.calculateTotalPrice();
        //       await this.stationPriceOnLoad();
        //     })
        //     .catch(() => {});
        // } else {
        //   done();
        // }
      }
    },
    // 工站单价
    async rowPriceSave(row, done, loading) {
      row.parentId = this.parentId;
      row.id = row.id || new Date().getTime() + '-id';
      this.stationPriceDialog.data.push(row);
      // 明细保存
      if (row.parentId) {
        // row.parentId =>找到工序 下的所有明细价格集合
        let children = this.stationPriceDialog.data.filter((d) => d.id == row.parentId);
        let childrenIndex = this.stationPriceDialog.data.findIndex((d) => d.id == row.parentId);
        if (children && children.length > 0) {
          let prices = children[0].children ? children[0].children.map((c) => c.price).concat(row.price) : [row.price];
          let result = await calculateRoutePrice(prices);
          if (result.data.code === 200) {
            let data = result.data.data;
            children[0].price = data;
            // 修改工序价格
            this.$set(this.stationPriceDialog.data[childrenIndex], 'price', data);
          }
        }
        await this.stationPriceOnLoad();
        await this.calculateTotalPrice();
        await this.stationPriceOnLoad();
      } else {
        await this.calculateTotalPrice();
        await this.stationPriceOnLoad();
      }
      // 格式化数据
      // this.stationPriceOnLoad();
      done();
    },
    async rowPriceUpdate(row, index, done, loading) {
      // 明细编辑
      if (row.parentId) {
        let children = this.stationPriceDialog.data.filter((d) => d.id == row.parentId);
        let childrenIndex = this.stationPriceDialog.data.findIndex((d) => d.id == row.parentId);

        if (children && children.length > 0) {
          let subIndex = children[0].children.findIndex((c) => c.id == row.id);
          this.$set(this.stationPriceDialog.data[childrenIndex].children[subIndex], 'price', row.price);
          let prices = children[0].children.map((c) => c.price);
          let result = await calculateRoutePrice(prices);
          if (result.data.code === 200) {
            let data = result.data.data;
            children[0].price = data;
            // 修改工序价格
            this.$set(this.stationPriceDialog.data[childrenIndex], 'price', data);
            await this.stationPriceOnLoad();
          }
        }
        await this.calculateTotalPrice();
        await this.stationPriceOnLoad();
        done(row);
      } else {
        // TODO:工序编辑
        done(row);
      }
    },
    // 修改合计
    async calculateTotalPrice() {
      this.stationPriceDialogLoading = true;
      this.stationPriceDialogLoadingText = '折后总价计算中，请稍后...';
      let allPrices = this.stationPriceDialog.data.map((d) => d.price);
      let allResult = await calculatePrice({
        priceCoefficient: this.stationPriceDialog.amountFormModel.rate,
        processRoutePriceList: allPrices
      });
      if (allResult.data.code === 200) {
        let data = allResult.data.data;
        // 修改合计价格
        this.stationPriceDialog.amountFormModel.totalPrice = data.totalPrice;
        this.stationPriceDialog.amountFormModel.discountPrice = data.discountPrice;
      }
      this.stationPriceDialogLoading = false;
    },
    // 修改系数
    changeRate(value) {
      if (this.stationPriceDialog.data.length > 0) {
        this.calculateTotalPrice();
      }
    },
    formatterToTreeData(data) {
      let parent = data.filter((d) => !d.parentId);
      let children = data.filter((d) => d.parentId);

      toTree(parent, children);

      function toTree(parent, children) {
        parent.map((p) => {
          children.map((cItem, cIndex) => {
            if (p.id == cItem.parentId) {
              let _c = JSON.parse(JSON.stringify(children));
              _c.splice(cIndex, 1);
              toTree([cItem], _c);
              if (p.children) {
                p.children.push(cItem);
              } else {
                p.children = [cItem];
              }
            }
          });
        });
      }

      return parent;
    },
    stationPriceOnLoad() {
      let copyData = deepClone(this.stationPriceDialog.data);
      this.stationPriceDialog.data = this.formatterToTreeData(copyData);
      this.groupSelectionClear();
    },
    beforePriceOpen(done, type) {
      if (type == 'edit') {
        let columns = this.stationPriceDialog.option.column;
        let priceIndex = columns.findIndex((c) => c.prop == 'price');
        let processRouteIdIndex = columns.findIndex((c) => c.prop == 'processRouteId');
        let partNoIndex = columns.findIndex((c) => c.prop == 'partNo');
        if (this.stationPriceDialog.form.parentId) {
          // 工站单价 允许输入
          columns[priceIndex].disabled = false;
          // 工站名称隐藏 物料名称显示
          columns[processRouteIdIndex].display = false;
          columns[partNoIndex].display = true;
        } else {
          // 工站单价 禁止输入
          columns[priceIndex].disabled = true;
          // 工站名称显示 物料名称隐藏
          columns[processRouteIdIndex].display = true;
          columns[partNoIndex].display = false;
        }
      }
      done();
    },
    beforePriceClose(done, type) {
      this.parentId = null;
      done();
    },
    groupSelectionChange(list) {
      this.stationPriceDialog.selectionList = list;
    },
    groupSelectionClear() {
      this.stationPriceDialog.selectionList = [];
      this.$refs.stationPriceCrud && this.$refs.stationPriceCrud.toggleSelection();
    },
    submitForm() {
      const that = this;
      that.$refs['basicInfoForm'].validate((valid, done) => {
        if (valid) {
          done();
          that.$refs['amountForm'].validate((valid, done) => {
            if (valid) {
              if (this.stationPriceDialog.data && this.stationPriceDialog.data.length == 0) {
                that.$message.warning('工站单价配置不能为空');
                done();
                return;
              }
              // 校验通过
              if (!that.isEditButtonStatus) {
                // 新增
                that.submitFormAdd();
              } else {
                // 编辑
                that.submitFormEdit();
              }
              done();
            }
          });
        }
      });
    },
    submitFormAdd() {
      const that = this;
      let { effectiveFrom, effectiveTo, partMasterId, partModel, partName, partNo, partType } = that.stationPriceDialog.basicInfoFormModel;
      let routePriceList = this.stationPriceDialog.data.map((d) => {
        return {
          price: d.price, //工序总价
          processId: that.processId, //产品工艺ID
          processRouteId: d.processRouteId, //工序ID
          remark: d.remark,
          routeName: d.routeName, // 工序名称
          routeCode: d.routeCode, // 工序编码
          routeType: d.routeType, // 工序类型
          sequence: d.sequence, //	工序排序
          routeDescription: d.routeDescription, // 加工内容
          materialPriceList: d.children
            ? d.children.map((c, i) => {
                return {
                  partMasterId: c.partMasterId, //物料ID
                  partNo: c.partNo, //物料编码
                  price: c.price, //物料单价
                  sequence: i + 1,
                  processId: that.processId, //产品工艺ID
                  description: c.routeDescription, // 加工内容
                  // processPriceId: 0, ????
                  remark: c.remark
                  // routePriceId: 0 //工序配置ID
                };
              })
            : []
        };
      });
      add({
        processId: that.processId,
        totalPrice: that.stationPriceDialog.amountFormModel.totalPrice, //所有工序总价之和
        rate: that.stationPriceDialog.amountFormModel.rate, //价格系数
        discountPrice: that.stationPriceDialog.amountFormModel.discountPrice, //折后价
        effectiveFrom, //生效日期
        effectiveTo, //失效日期
        partMasterId, //产品id
        partModel, //产品型号
        partName, //	产品名称
        partNo, //产品编码
        partType, //产品类型
        routePriceList
      })
        .then(() => {
          this.stationPriceDialogClose();
          this.onLoad(this.page);
        })
        .catch((err) => {});
    },
    submitFormEdit() {
      const that = this;
      let { effectiveFrom, effectiveTo, partMasterId, partModel, partName, partNo, partType } = that.stationPriceDialog.basicInfoFormModel;
      let routePriceList = this.stationPriceDialog.data.map((d) => {
        let obj = {
          id: d.id,
          processPriceId: d.processPriceId,
          price: d.price, //工序总价
          processId: that.processId, //产品工艺ID
          processRouteId: d.processRouteId, //工序ID
          remark: d.remark,
          routeName: d.routeName, // 工序名称
          routeCode: d.routeCode, // 工序编码
          routeType: d.routeType, // 工序类型
          sequence: d.sequence, //	工序排序
          routeDescription: d.routeDescription, // 加工内容
          materialPriceList: d.children
            ? d.children.map((c, i) => {
                let cobj = {
                  id: c.id,
                  processPriceId: c.processPriceId,
                  partMasterId: c.partMasterId, //物料ID
                  partNo: c.partNo, //物料编码
                  price: c.price, //物料单价
                  sequence: i + 1,
                  processId: that.processId, //产品工艺ID
                  description: c.routeDescription, // 加工内容
                  remark: c.remark,
                  routePriceId: c.routePriceId //工序配置ID
                };
                if (c.id.includes('-id')) {
                  delete cobj.id;
                }
                return cobj;
              })
            : []
        };
        if (d.id.includes('-id')) {
          delete obj.id;
        }
        return obj;
      });
      add({
        id: that.editData.id,
        status: that.editData.status,
        processId: that.processId,
        totalPrice: that.stationPriceDialog.amountFormModel.totalPrice, //所有工序总价之和
        rate: that.stationPriceDialog.amountFormModel.rate, //价格系数
        discountPrice: that.stationPriceDialog.amountFormModel.discountPrice, //折后价
        effectiveFrom, //生效日期
        effectiveTo, //失效日期
        partMasterId, //产品id
        partModel, //产品型号
        partName, //	产品名称
        partNo, //产品编码
        partType, //产品类型
        routePriceList
      })
        .then((res) => {
          that.editData = null;
          that.stationPriceDialogClose();
          that.onLoad(this.page);
        })
        .catch(() => {})
        .finally(() => {});
    },
    closeDialog() {
      this.stationPriceDialogClose();
    },
    // 工站单价弹窗打开
    stationPriceDialogOpen() {
      this.routeList = [];
      this.processId = '';
      this.stationPriceDialog.data = [];
      // this.stationPriceOnLoad();
    },
    // 工站单价弹窗关闭
    stationPriceDialogClose() {
      this.$refs.basicInfoForm && this.$refs.basicInfoForm.resetFields();
      this.$refs.amountForm && this.$refs.amountForm.resetFields();
      this.stationPriceDialog.amountFormModel.rate = 100;
      this.stationPriceDialog.visible = false;
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    },
    handleTabClick() {
      this.$nextTick(() => {
        this.$structuralSplit('单价配置');
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.subTitle {
  font-size: 16px;
  font-weight: bold;
  color: rgba(0, 0, 0, 0.85);
  .mr10 {
    margin-right: 10px;
  }
}
</style>
